package com.deepblue.image.maker.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 本地Session缓存
 *
 * @author yymagicer
 * @version 1.0
 * @date 2021/11/10 下午5:06
 */
@Component
public class LocalWebsocketSessionCache implements WebsocketSessionCache {


    private final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private  final AtomicInteger ONLINE_NUM = new AtomicInteger();

    @Override
    public void set(String key, WebSocketSession session) {
        sessionMap.put(key,session);
    }

    @Override
    public WebSocketSession get(String key) {
        return sessionMap.get(key);
    }


    @Override
    public WebSocketSession remove(String key) {
        return sessionMap.remove(key);
    }

    @Override
    public int incrementAndGet() {
        return ONLINE_NUM.incrementAndGet();
    }

    @Override
    public int decrementAndGet() {
        return ONLINE_NUM.decrementAndGet();
    }

    @Override
    public int get() {
        return ONLINE_NUM.get();
    }
}
